// ignore_for_file: use_build_context_synchronously, unnecessary_null_comparison

import 'dart:collection';
import 'dart:io';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:verse_systems/commom/global/global.dart';
import 'package:verse_systems/commom/global/jpush_service.dart';
import 'package:verse_systems/commom/provider/common_provider.dart';
import 'package:verse_systems/commom/routers/custom_route_animation.dart';
import 'package:verse_systems/commom/routers/routes.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/widgets/alert.dart';
import 'package:package_info_plus/package_info_plus.dart';

bool hookOut = true;

class NavigatorUtils {
  static BuildContext context =
      Global.navigatorKey.currentState!.overlay!.context;

  static goToLogin() {
    Navigator.push(NavigatorUtils.context,
        CustomRouteAnimation(routePage: const LoginPage()));
  }

  static goToHome() {
    /**
   *  底部弹出向上  
   *  
   * Navigator.push(NavigatorUtils.context,
        CustomRouteAnimation(routePage: const TabbarPages()));
   * 
   * Get.to(() => const TabbarPages(),
        fullscreenDialog: true,
        transition: Transition.downToUp,
        popGesture: true);
   */
    Get.offAllNamed(RoutesPage.Application);
  }

  static goToChangeContact() {
    Provider.of<CommonProvider>(context, listen: false).changeIndex(1);
  }

  static goToChangeHome() {
    Provider.of<CommonProvider>(context, listen: false).changeIndex(0);
  }


  static logOut() {
    Alert.showAlert(
        title: "tips".tr,
        confirm: "quit".tr,
            cancel: "cancel".tr,
        content: "confirm_exit".tr,
        onPressed: loggedOuts);
  }

  static hook401() {
    if (hookOut) {
      Alert.showAlert(
          title: "tips".tr,
          confirm: "confirm".tr,
             cancel: "cancel".tr,
          content: "login_error_again".tr,
          onPressed: loggedOuts);
      hookOut = false;
    }
  }

  static loggedOuts() async {
    Loading.show("loading".tr);
    final clearAll = await AccountUtil.clearAll();
    if (clearAll) {
      JPUSHService.deleteAlias();
      Future.delayed(const Duration(milliseconds: 100), () {
        Loading.dismiss();
        NavigatorUtils.goToChangeHome();
        Get.offAllNamed(RoutesPage.Login);
      });
    }
  }

  static handleProtocol() async {
    String fileUrl = "http://new.kingpig666.com/protocols/user-agreement";
    WebViewPage.pushRouter(context, fileUrl, title: '');
  }

  static handlePrivacy() async {
    String fileUrl = "http://new.kingpig666.com/protocols/privacy-agreement";
    WebViewPage.pushRouter(context, fileUrl, title: '');
  }

  static handleProductWeb({required String url}) {
    WebViewPage.pushRouter(context, url, title: '');
  }

  static void handleAppVersion({
    required void Function(bool value) success,
  }) {
    Map<String, dynamic> map = HashMap();
    if (Platform.isAndroid) {
      map['device_type'] = "1";
    } else {
      map['device_type'] = "2";
    }
    Request.postCallback(
      HttpUrls.getAppVersion,
      data: map,
      needToken: false,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("需要升级信息----->${result.data}");
        if (result.status == 0) {
          success(true);
          PackageInfo packageInfo = await PackageInfo.fromPlatform();
          String version = packageInfo.version;
          final String appVersion = result.data["version"];
          debugPrint("需要升级信息version----->$version");
          if (int.parse(appVersion) > int.parse(version)) {

          Future.delayed(const Duration(milliseconds: 500), () async {
                 //需要升级
            Alert.showAPPVersionsSheet(onCancel: () async {
              exit(0);
            }, onPressed: () async {
              String productUrl = result.data["upgrade_link"];
              if (await canLaunchUrl(Uri.parse(productUrl))) {
                await launchUrl(Uri.parse(productUrl));
              } else {
                throw 'Could not launch $productUrl';
              }
            });
            
           });

          
          }
        }
      },
      error: (err) async {
      success(true);
        //替换新域名
        debugPrint("请求出错了信息----->$err");
        Request.requestWithMetod(
          HttpUrls.getAppVersion,
          data: map,
          needToken: false,
        ).then((res) async {
          final String baseUrl =  res.toString();  
          final bool status = await AccountUtil.setAppBaseUr(baseUrl);
          debugPrint("请求新域名返回----->$baseUrl---缓存$status");
          if (status) {
             //重新调用版本检测
             handleAppVersion(success: (bool value) {  
              
             });
          } 
        });
      },
    );
  }
}
